using System;
using System.Data;
using System.Xml;
using vs.Core;

namespace Forum
{
    public partial class forum_search : Window
    {
        private const int PAGESIZE = 20;
        protected vs.Paging.vsPaging pager;

        private void Paging(string w, int currentPage)
        {
            pager.Visible = false;
            string strSQL = @"SELECT count(r.ReplyID)
                            FROM FORUM_Reply r INNER JOIN FORUM_Topic t ON r.TopicID = t.TopicID
                            WHERE (r.Content LIKE N'%@@w%') OR (t.TopicName = N'%@@w%')";
            strSQL = strSQL.Replace("@@w", w);

            object o = DataFactory.ExecuteScalar(strSQL);
            if (o != null)
            {
                int count = Convert.ToInt32(o);
                int pgs = count / PAGESIZE;
                if (PAGESIZE * pgs < count) pgs++;

                if (pgs >= 2)
                {
                    pager.Visible = true;
                    string desk = PortalUtils.CurrentDesktopName;
                    string format = UrlProvider.DesktopUrl(desk) + "?pg=@@page&w=" + w;
                    pager.showing(pgs, currentPage, format);
                }
            }
        }

        private XmlDocument LoadData(DataTable dt)
        {

            string topicdesk = this.GetModuleSetting("topicdesk");
            XmlDocument doc = new XmlDocument();
            doc.LoadXml("<search></search>");

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string content = dt.Rows[i]["Content"].ToString();
                content = CommonFunction.ToHtmlContent(content);
                DateTime postedDate = Convert.ToDateTime(dt.Rows[i]["PostedDate"]);
                DateTime topicDate = Convert.ToDateTime(dt.Rows[i]["TopicDate"]);
                string link = UrlProvider.DesktopUrl(topicdesk, dt.Rows[i]["TopicID"].ToString());

                XmlElement item = doc.CreateElement("item");
                CommonFunction.AddNode(doc, item, "Content", content);
                CommonFunction.AddNode(doc, item, "TopicName", dt.Rows[i]["TopicName"].ToString());
                CommonFunction.AddNode(doc, item, "TopicDate", CommonFunction.ToDateString(topicDate, "dd-MM-yy"));
                CommonFunction.AddNode(doc, item, "Creator", dt.Rows[i]["Creator"].ToString());
                CommonFunction.AddNode(doc, item, "UserName", dt.Rows[i]["UserName"].ToString());
                CommonFunction.AddNode(doc, item, "PostedDate", CommonFunction.ToDateString(postedDate, "dd-MM-yy"));
                CommonFunction.AddNode(doc, item, "link", link);
                doc.DocumentElement.AppendChild(item);
            }

            return doc;
        }

        private void Searching()
        {
            if (Request.QueryString["w"] == null) return;
            

            string w = DataFactory.NormalizeLikeString(Request.QueryString["w"]);
            string strSQL = @"SELECT r.Content, t.TopicName, r.UserName, r.PostedDate, t.TopicID, 
                            t.PostedDate AS TopicDate, t.Creator
                            FROM FORUM_Reply r INNER JOIN FORUM_Topic t ON r.TopicID = t.TopicID
                            WHERE (r.Content LIKE N'%@@w%') OR (t.TopicName = N'%@@w%')
                            ORDER BY r.PostedDate DESC";
            
            strSQL = strSQL.Replace("@@w", w);
            int currentPage = 0;
            if (Request.QueryString["pg"] != null)
                currentPage = Convert.ToInt32(Request.QueryString["pg"]) - 1;
            int startRecord = currentPage * PAGESIZE;
            DataTable dt = DataFactory.LoadPage(strSQL, startRecord, PAGESIZE);
            txtWhat.Text = w;
            
            XmlDocument doc = LoadData(dt);
            string skin = ModSettingController.GetModuleSetting("skin", Utils.ModuleID);
            string template = engine_xml.get_template_folder(skin) + "forum_search.xsl";
            CommonFunction.XMLTransform(xml, template, doc);
            Paging(w, currentPage);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    Searching();
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtWhat.Text.Trim() == "") return;

                string deskname = PortalUtils.CurrentDesktopName;
                string url = UrlProvider.DesktopUrl(deskname) + "?w=" + txtWhat.Text.Trim();
                Response.Redirect(url);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    }
}